<?php

namespace app\index\controller;

use app\BaseApiController;
use app\common\mqtt\MqttService;
use PhpMqtt\Client\Exceptions\MqttClientException;

class MqttDemo extends BaseApiController
{
    /**
     * 健康检查/连接测试
     */
    public function ping()
    {
 
        try {
            $mqtt = new MqttService();
            $mqtt->connect();
            $mqtt->disconnect();
            return $this->success(['ok' => true], 'MQTT 连接成功');
        } catch (MqttClientException $e) {
            return $this->error('MQTT 连接失败：' . $e->getMessage());
        }
    }

    /**
     * 发布消息 Demo
     * POST /mqtt/publish
     * body: topic, message, qos(可选), retain(可选)
     */
    public function publish()
    {
        // $params = $this->getParams([
        //     'topic|主题' => 'require|max:200',
        //     'message|消息' => 'require|max:2000',
        //     'qos|服务质量' => 'number|in:0,1,2',
        //     'retain|保留消息' => 'in:0,1'
        // ]);
        $params['topic'] = 'testtopic/abc';
        $params['message'] = 'hello world'; 
        $params['qos'] = 0;
        $params['retain'] = 0;
        try {
            $mqtt = new MqttService();
            $mqtt->publish(
                $params['topic'],
                (string) $params['message'],
                isset($params['qos']) ? (int) $params['qos'] : null,
                isset($params['retain']) ? (bool) $params['retain'] : null
            );
            $mqtt->disconnect();

            return $this->success([
                'topic' => $params['topic'],
                'qos' => isset($params['qos']) ? (int) $params['qos'] : (int) config('mqtt.default_qos'),
                'retain' => isset($params['retain']) ? (bool) $params['retain'] : (bool) config('mqtt.default_retain')
            ], '发布成功');
        } catch (MqttClientException $e) {
            return $this->error('发布失败：' . $e->getMessage());
        }
    }
}


